require 'timeout'
IRCBot::Plugin.define 'isdown' do
	help_string "Checks if a website is up or down. Ask as \"isdown address.com\" or \"Marco, is <address> down?\""
	
	def isdown(address)
		begin
			timeout(5) do
				@sock = TCPSocket.new(address,80)
			end
		rescue Exception
			return true
		else
			@sock.close
			return false
		end
		@sock = nil
	end
	
	def command(user,target,message,hostmask)
		if !message.empty? then
			status = isdown(message)
			if status
				privmsg(target,"Site is down!")
			else
				privmsg(target,"It's just you, it's up and running.")
			end
		else
			privmsg(target,"Hey, gimme something to check.")
		end
	end
	
	def privmsg_function(user,target,message,hostmask)
		message = message.downcase
		if message.start_with?("#{$config[$network]['nickname']}, is ".downcase) and message.end_with?(' down?') then
			message = message.sub("#{$config[$network]['nickname']}, is ".downcase,'')
			address = message.strip.split[0]
			status = isdown(address)
			if status then
				privmsg(target,"Yeah, #{address} is down.")
			else
				privmsg(target,"No, it's just you.")
			end
		end
	end
end
